const iot = require('alibabacloud-iot-device-sdk');

const deviceClients = {}

function connect(deviceList) {
    if (!deviceList || deviceList.length === 0) {
        console.log("iotClient#online : deviceList empty!");
        return Promise.resolve();
    }

    const connectionPromises = deviceList.map(item => {
        return new Promise((resolve, reject) => {
            if (deviceClients[item.dn]) {
                return resolve();
            }

            console.log("connect device pk: %s, dn: %s, secret: %s", item.pk, item.dn, item.ds);
            const device = iot.device({
                productKey: item.pk,
                deviceName: item.dn,
                deviceSecret: item.ds,
                regionId: 'cn-shanghai'
            });

            device.on('connect', () => {
                console.log('%s#%s connect successfully!', item.pk, item.dn);
                deviceClients[item.dn] = device;
                resolve();  // 设备连接成功，解决 Promise
            });

            device.on("offline", () => {
                console.log('%s#%s offline!', item.pk, item.dn);
            });

            device.on("close", () => {
                console.log('%s#%s close!', item.pk, item.dn);
                delete deviceClients[item.dn];
            });

            device.on("error", (err) => {
                console.log('%s#%s error: %s', item.pk, item.dn, err.message);
                reject(err);  // 设备连接出错，拒绝 Promise
            });
        });
    });

    return Promise.all(connectionPromises);  // 返回一个等待所有设备连接成功的 Promise
}

module.exports = {
    deviceClients,
    connect
}